package com.zst.demo2.controller;


import com.zsr.entities.CommonResult;
import com.zsr.entities.RoleDTO;
import com.zsr.entities.UserDTO;
import com.zst.demo2.po.UserRolePO;
import com.zst.demo2.service.Demo3FeignService;
import com.zst.demo2.service.IUserRoleService;
import com.zst.demo2.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Optional;

@RestController
@RequestMapping("/zst/demo2")
@Slf4j
public class IndexController {

    @Resource
    Demo3FeignService demo3FeignService;

    @Autowired
    IUserService iUserService;

    @Autowired
    IUserRoleService iUserRoleService;

    @GetMapping("/index")
    public String index() {
        log.info("this is demo2 application.");
        return "this is demo3 application.";
    }

    @GetMapping("/get-user-base/{id}")
    public CommonResult<UserDTO> getUserBase(@PathVariable("id") Long id) {
        // 调用用户信息
        Optional<UserDTO> userDTOOpt = iUserService.getUserById(id);
        if (!userDTOOpt.isPresent()) {
            return CommonResult.ResultSuccess(null);
        }
        UserDTO userDTO = userDTOOpt.get();
        if (Objects.isNull(userDTO.getId())) {
            return CommonResult.ResultSuccess(null);
        }
        // 获取角色Id
        Optional<UserRolePO> userRoleOpt = iUserRoleService.getUserRoleById(userDTO.getId());
        if (!userRoleOpt.isPresent()) {
            return CommonResult.ResultSuccess(userDTO);
        }
        // 获取角色信息
        CommonResult<RoleDTO> role = demo3FeignService.getRole(userRoleOpt.get().getId());
        if (Objects.nonNull(role.getData())) {
            userDTO.getRoleList().add(role.getData());
        }
        return CommonResult.ResultSuccess(userDTO);
    }

    @GetMapping(value = "/get-only-user/{id}")
    public CommonResult<UserDTO> getOnlyUser(@PathVariable("id") Long id) {
        // 调用用户信息
        Optional<UserDTO> userDTOOpt = iUserService.getUserById(id);
        if (!userDTOOpt.isPresent() || Objects.isNull(userDTOOpt.get().getId())) {
            return CommonResult.ResultSuccess(null);
        }
        return CommonResult.ResultSuccess(userDTOOpt.get());
    }
}